﻿using System;
using System.IO;
using System.Net;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Data;
using Negocio;
using System.Windows;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Windows.Controls;
using Microsoft.Win32;



namespace Presentacion
{
    /// <summary>
    /// Lógica de interacción para WExecuteTest.xaml
    /// </summary>
    public partial class WExecuteTest : UserControl
    {
        
        private Club club;
        DataTable table;
        ObservableCollection<PlayerExecution> plyExecListToUpd;
        ObservableCollection<string> plyNameList;
        private bool insertExecutions;
        private Principal principal;

        public WExecuteTest(Principal p)
        {
            InitializeComponent();
            principal = p;
            club = Club.getInstance();
            table = new DataTable();
            plyNameList = new ObservableCollection<string>();
            plyExecListToUpd = new ObservableCollection<PlayerExecution>();
            cbxEvaluation.ItemsSource = club.Evaluations;
            cbxGroup.ItemsSource = club.Groups;
            cbxEvaluation.ItemsSource = club.Evaluations;
            dpEvaluationDate.SelectedDate = DateTime.Today;
            cbxEvaluationToUpdate.ItemsSource = club.loadEvaluationWithGroup(DateTime.Today);
            insertExecutions = true;
        }

        //public static WExecuteTest getInstance(Principal p)
        //{
        //    if (instance == null)
        //    {
        //        instance = new WExecuteTest(p);
        //    }
        //    return instance;
        //}


        private void cbxEvaluation_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (cbxEvaluation.SelectedIndex != -1 && cbxGroup.SelectedIndex != -1)
            {
                int posEvaluation = cbxEvaluation.SelectedIndex;
                int posGroup = cbxGroup.SelectedIndex;
                loadTable(club.Groups[posGroup], club.Evaluations[posEvaluation]);
                dataGrid1.ItemsSource = table.DefaultView;
                cbxEvaluationToUpdate.SelectedIndex = -1;
            }
            insertExecutions = true;            
        }

        private void btnEnter_Click(object sender, RoutedEventArgs e)
        {
            bool ok = insertData(sender, e);
            if (ok)
            {
                MessageBox.Show("Se ingresaron los datos", "Atención", MessageBoxButton.OK, MessageBoxImage.Information);
            }            
        }

        private bool insertData(object sender, RoutedEventArgs e)
        {
            bool insertOk = true;
            int pos = cbxEvaluation.SelectedIndex;
            int posGroup = cbxGroup.SelectedIndex;
            try
            {
                if (insertExecutions)
                {
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        DataRow row = table.Rows[i];
                        ObservableCollection<TestValue> testValueList = new ObservableCollection<TestValue>();
                        for (int j = 1; j < table.Columns.Count; j++)
                        {
                            TestValue testValue = club.newTestValue(club.testByName(table.Columns[j].ColumnName), row[table.Columns[j].ColumnName].ToString());
                            testValueList.Add(testValue);
                        }
                        PlayerExecution pExecution = club.newPlayerExecution(club.Evaluations[pos].Name, club.Groups[posGroup].Name, club.playerByName(row["Jugador"].ToString()), testValueList, "", DateTime.Today);
                        club.calculateValuesOfExecution(pExecution);
                        club.addPlayerExecution(pExecution);
                    }
                    loadTable(club.Evaluations[pos].Name + "," + club.Groups[posGroup].Name, DateTime.Today);
                    plyExecListToUpd.Clear();
                    plyNameList.Clear();
                    plyNameList = club.loadEvaluationWithGroup(DateTime.Today);
                    cbxEvaluationToUpdate.ItemsSource = null;
                    cbxEvaluationToUpdate.ItemsSource = plyNameList;
                    dpEvaluationDate.SelectedDate = DateTime.Today;
                    string evaluationGroupName = club.Evaluations[pos].Name + ", " + club.Groups[posGroup].Name;
                    int posNew = 0;
                    for (int i = 0; i < plyNameList.Count; i++)
                    {
                        if (evaluationGroupName.Equals(plyNameList[i]))
                        {
                            posNew = i;
                            i = plyNameList.Count;
                        }
                    }
                    cbxEvaluationToUpdate.SelectedIndex = posNew;

                }
                else
                {
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        PlayerExecution pExecution = plyExecListToUpd[i];
                        DataRow row = table.Rows[i];
                        for (int j = 1; j < table.Columns.Count; j++)
                        {
                            club.updateTestValue(club.testByName(table.Columns[j].ColumnName), row[plyExecListToUpd[i].Values[j - 1].Test.Name].ToString(), plyExecListToUpd[i].Values[j - 1]);
                        }
                        club.updatePlayerExecution(pExecution.EvaluationName, pExecution.GroupName, pExecution.Player, pExecution.Values, pExecution.Date, pExecution.Comments, pExecution);

                    }
                    if (cbxEvaluation.SelectedIndex != 0)
                    {
                        loadTable(plyNameList[cbxEvaluationToUpdate.SelectedIndex], DateTime.Today);
                    }

                }                
            }
            catch (ArgumentOutOfRangeException)
            {
                insertOk = false;
            }
            return insertOk;
        }

        private void cbxEvaluationToUpdate_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int posEvaluationToUpdate = cbxEvaluationToUpdate.SelectedIndex;
            if (posEvaluationToUpdate != -1)
            {
                cbxEvaluation.SelectedIndex = -1;
                cbxGroup.SelectedIndex = -1;
                loadTable(plyNameList[posEvaluationToUpdate], dpEvaluationDate.SelectedDate.Value);
            }
            
        }

        private void dpEvaluationDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            plyNameList = club.loadEvaluationWithGroup(dpEvaluationDate.SelectedDate.Value);
            cbxEvaluationToUpdate.ItemsSource = null;
            cbxEvaluationToUpdate.ItemsSource = plyNameList;
            insertExecutions = false;
        }

        private void loadTable(Group oneGroup, Evaluation oneEvaluation)
        {

            table.Clear();
            table.Columns.Clear();
            dataGrid1.ItemsSource = null;
            IEnumerator<Test> p = oneEvaluation.Tests.GetEnumerator();
            DataColumn colJug = new DataColumn("Jugador", typeof(string));
            table.Columns.Add(colJug);
            colJug.ReadOnly = true;
            while (p.MoveNext())
            {
                DataColumn colTest = new DataColumn(p.Current.Name, typeof(float));
                if (!p.Current.Sequence.Equals("n/a"))
                {
                    colTest.ReadOnly = true;
                }
                table.Columns.Add(colTest);

            }

            IEnumerator<Player> iplayers = oneGroup.Players.GetEnumerator();
            p.Reset();
            while (iplayers.MoveNext())
            {
                DataRow row = table.NewRow();
                row["Jugador"] = iplayers.Current.CompleteName;
                while (p.MoveNext())
                {
                    row[p.Current.Name] = 0;
                }
                p.Reset();
                table.Rows.Add(row);
            }
            dataGrid1.FrozenColumnCount = 1;
            dataGrid1.ItemsSource = table.DefaultView;
        }

        private void loadTable(string groupName, DateTime exeuteDate)
        {
            table.Clear();
            table.Columns.Clear();
            dataGrid1.ItemsSource = null;
            plyExecListToUpd = club.loadPlayersExecutionByDate(exeuteDate, groupName);
            IEnumerator<PlayerExecution> plyexec = plyExecListToUpd.GetEnumerator();
            DataColumn colJug = new DataColumn("Jugador", typeof(string));
            table.Columns.Add(colJug);
            colJug.ReadOnly = true;
            bool columnsComplete = false;
            while (plyexec.MoveNext())
            {
                IEnumerator<TestValue> p = plyexec.Current.Values.GetEnumerator();
                while (p.MoveNext() && columnsComplete == false)
                {
                    DataColumn colTest = new DataColumn(p.Current.Test.Name, typeof(float));
                    if (!p.Current.Test.Sequence.Equals("n/a"))
                    {
                        colTest.ReadOnly = true;
                    }
                    table.Columns.Add(colTest);
                }
                columnsComplete = true;
                p.Reset();
                DataRow row = table.NewRow();
                while (p.MoveNext())
                {

                    row["Jugador"] = plyexec.Current.Player.CompleteName;
                    row[p.Current.Test.Name] = p.Current.ValueExecution;

                }
                table.Rows.Add(row);
                p.Reset();
            }
            dataGrid1.FrozenColumnCount = 1;
            dataGrid1.ItemsSource = table.DefaultView;
            insertExecutions = false;
        }

        private void cbxGroup_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxEvaluation.SelectedIndex != -1 && cbxGroup.SelectedIndex != -1)
            {
                cbxEvaluationToUpdate.SelectedIndex = -1;
                int posEvaluation = cbxEvaluation.SelectedIndex;
                int posGroup = cbxGroup.SelectedIndex;
                loadTable(club.Groups[posGroup], club.Evaluations[posEvaluation]);
            }
            insertExecutions = true;            
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog v = new SaveFileDialog();
            v.Filter = "Excel(*.csv)|*.csv|Todos los Archivos(*.*)|*.*";
            v.AddExtension = true;
            v.DefaultExt = ".csv";
            bool yes = v.ShowDialog().Value;
            if (yes)
            {
                try
                {
                    int posEvaluationToUpdate = cbxEvaluationToUpdate.SelectedIndex;
                    string evaluationName = plyNameList[posEvaluationToUpdate];
                    this.club.writePlayersExecutionToFile(dpEvaluationDate.SelectedDate.Value, evaluationName, v.FileName);
                }
                catch (ArgumentOutOfRangeException)
                {
                    MessageBox.Show("Seleccione un archivo válido", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                catch (IndexOutOfRangeException)
                {
                    MessageBox.Show("Seleccione un archivo válido", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog v = new OpenFileDialog();
            v.Filter = "Excel(*.csv)|*.csv|Todos los Archivos(*.*)|*.*";
            v.AddExtension = true;
            v.DefaultExt = ".csv";
            bool yes = v.ShowDialog().Value;
            if (yes)
            {
                try
                {
                    this.club.readPlayersExecutionFromFile(plyExecListToUpd, v.FileName);
                    loadTable(cbxEvaluationToUpdate.Text, dpEvaluationDate.SelectedDate.Value);
                }
                catch (ArgumentOutOfRangeException)
                {
                    MessageBox.Show("Seleccione un archivo válido", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                catch (IndexOutOfRangeException)
                {
                    MessageBox.Show("Seleccione un archivo válido", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private void dataGrid1_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            //int pos = dataGrid1.SelectedIndex;
            //if (insertExecutions)
            //{
                
            //    string evaluationGroupNames = ((Evaluation)cbxEvaluation.SelectedItem).Name + ","+ ((Group)cbxGroup.SelectedItem).Name;
            //    insertData(sender, e);
            //    ObservableCollection<PlayerExecution> plExecList=club.loadPlayersExecutionByDate(DateTime.Today, evaluationGroupNames);
            //    WPlayersEnterData wPlayerEnterData = new WPlayersEnterData(pos,plExecList);
            //    principal.getGrid().Children.Clear();
            //    principal.getGrid().Children.Add(wPlayerEnterData);
            //}
            //else
            //{
            //    WPlayersEnterData wPlayerEnterData = new WPlayersEnterData(dataGrid1.SelectedIndex,plyExecListToUpd);
            //    principal.getGrid().Children.Clear();
            //    principal.getGrid().Children.Add(wPlayerEnterData);
            //    loadTable(plyNameList[cbxEvaluationToUpdate.SelectedIndex], dpEvaluationDate.SelectedDate.Value);
            //}
        }

        private void dataGrid1_MouseRightButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            int pos = dataGrid1.SelectedIndex;
            if (insertExecutions)
            {

                string evaluationGroupNames = ((Evaluation)cbxEvaluation.SelectedItem).Name + "," + ((Group)cbxGroup.SelectedItem).Name;
                insertData(sender, e);
                ObservableCollection<PlayerExecution> plExecList = club.loadPlayersExecutionByDate(DateTime.Today, evaluationGroupNames);
                WPlayersEnterData wPlayerEnterData = new WPlayersEnterData(pos, plExecList);
                principal.getGrid().Children.Clear();
                principal.getGrid().Children.Add(wPlayerEnterData);
            }
            else
            {
                WPlayersEnterData wPlayerEnterData = new WPlayersEnterData(dataGrid1.SelectedIndex, plyExecListToUpd);
                principal.getGrid().Children.Clear();
                principal.getGrid().Children.Add(wPlayerEnterData);
                loadTable(plyNameList[cbxEvaluationToUpdate.SelectedIndex], dpEvaluationDate.SelectedDate.Value);
            }
        }
    }
}
